package jmine.tec.persist.schema.impl.parsers;

import java.util.regex.Matcher;

import jmine.tec.persist.schema.impl.elements.ForeignKeyElement;
import jmine.tec.persist.schema.impl.elements.Schema;

/**
 * Parser de foreign keys
 * 
 * @author lundberg
 */
public class ForeignKeyParser extends AbstractSchemaElementParser<ForeignKeyElement> {

    private static final int REFERENCING_TABLE_NAME_GROUP_INDEX = 1;

    private static final int FK_NAME_GROUP_INDEX = 2;

    private static final int REFERENCING_COLUMNS_GROUP_INDEX = 3;

    private static final int REFERENCED_TABLE_NAME_GROUP_INDEX = 4;

    private static final int REFERENCED_COLUMNS_GROUP_INDEX = 5;

    private static final int ON_DELETE_CASCADE_INDEX = 6;

    /**
     * Construtor
     * 
     * @param schema o schema
     */
    public ForeignKeyParser(Schema schema) {
        super("alter\\s+table\\s+(" + TableParser.TABLE_NAME_REGEX
                + ")\\s+add\\s+constraint\\s+(\\S+)\\s+foreign\\s+key\\s+\\(([\\w\\s,]+)\\)\\s+" + "references\\s+("
                + TableParser.TABLE_NAME_REGEX + ")(?:\\s+\\(([\\w\\s,]+)\\))?(\\s+on delete cascade)?", schema);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ForeignKeyElement doParse(Matcher matcher) {
        String referencing = matcher.group(REFERENCING_TABLE_NAME_GROUP_INDEX);
        String referenced = matcher.group(REFERENCED_TABLE_NAME_GROUP_INDEX);
        String[] referencingColumns = matcher.group(REFERENCING_COLUMNS_GROUP_INDEX).replaceAll("\\s", "").split(",");
        String[] referencedColumns = null;
        if (matcher.group(REFERENCED_COLUMNS_GROUP_INDEX) != null) {
            referencedColumns = matcher.group(REFERENCED_COLUMNS_GROUP_INDEX).replaceAll("\\s", "").split(",");
        }
        boolean onDeleteCascade = matcher.group(ON_DELETE_CASCADE_INDEX) != null;
        String fkName = matcher.group(FK_NAME_GROUP_INDEX);
        return new ForeignKeyElement(referencing, referenced, referencingColumns, referencedColumns, fkName, this.getSchema(),
                onDeleteCascade);
    }
}
